Telegram Integration Testing Guide
**Phase:** 37 OpenClaw Integration
**Last Updated:** 2026-02-16
Overview
This guide walks through testing the Telegram bot integration for Atom Agent OS, including account linking, command execution, and response formatting.
Prerequisites
1. Environment Setup
Ensure you have:
- Atom backend running (http://localhost:8000 or https://api.atomagentos.com)
- PostgreSQL database with migrations applied
- Redis instance running (for account linking tokens)
- Existing tenant and user account in Atom
2. Required Environment Variables
Create or update .env file in backend-saas/:
# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN=your_bot_token_here
# Redis Configuration (for account linking)
REDIS_URL=redis://localhost:6379/0
# Or use Upstash REST API:
# REDIS_URL=https://your-redis-url.upstash.io
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/atomdb
# Application
PORT=8000
LOG_LEVEL=INFO3. Install Python Dependencies
cd backend-saas
pip install python-telegram-bot==22.0
pip install redisStep 1: Create Telegram Bot
1.1. Start Conversation with BotFather
- Open Telegram and search for
@BotFather - Send
/newbotcommand - Follow prompts:
- Choose a name:
Atom Agent OS Test Bot - Choose a username:
atom_test_bot_12345(must be unique)
- BotFather will provide a token like:
1.2. Configure Bot Settings (Optional but Recommended)
Send these commands to @BotFather:
/setprivacy
→ Select your bot
→ Disable**Why:** Allows bot to read all messages in groups (useful for testing)
/setcommands
→ Select your bot
→ Paste command list:
start - Start using Atom Agent OS
link - Link your Telegram account to Atom
help - Show available commands
status - Check agent statusStep 2: Configure Webhook
2.1. Get Webhook URL
**Local Development (with ngrok):**
# Install ngrok
brew install ngrok
# Start ngrok tunnel
ngrok http 8000
# Use the HTTPS URL provided:
# https://abc123.ngrok.io**Production (Managed Cloud):**
https://api.atomagentos.com2.2. Set Webhook via API
curl -X POST "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-domain.com/api/gateway/webhook/telegram"
}'**Replace:**
<TELEGRAM_BOT_TOKEN>with your actual tokenhttps://your-domain.comwith your domain
2.3. Verify Webhook
curl "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/getWebhookInfo"Expected response:
{
"ok": true,
"result": {
"url": "https://your-domain.com/api/gateway/webhook/telegram",
"has_custom_certificate": false,
"pending_update_count": 0
}
}Step 3: Link Telegram Account
3.1. Generate Link Token via API
curl -X POST "http://localhost:8000/api/gateway/link/telegram" \
-H "Content-Type: application/json" \
-d '{
"user_id": "your-tenant-user-id"
}'Expected response:
{
"token": "abc123def456",
"expires_at": "2026-02-16T03:00:00Z"
}3.2. Link Account via Telegram
Send this message to your bot:
/link abc123def456Or use the backend API:
curl -X POST "http://localhost:8000/api/gateway/confirm-link" \
-H "Content-Type: application/json" \
-d '{
"token": "abc123def456",
"chat_id": "your_telegram_chat_id"
}'**How to get your chat_id:**
- Send
/startto your bot - Visit:
https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/getUpdates - Find
"chat":{"id":123456789}in the response
3.3. Verify Linking
Check database or call:
curl "http://localhost:8000/api/gateway/linked-accounts?user_id=your-user-id"Step 4: Test Command Execution
4.1. Create Test Agent
First, ensure you have an agent in Atom:
curl -X POST "http://localhost:8000/api/agents" \
-H "Content-Type: application/json" \
-d '{
"name": "Finance",
"category": "Operations",
"maturity_level": "supervised",
"description": "Finance operations agent"
}'4.2. Send Command via Telegram
Send this message to your bot:
/run Finance show status4.3. Expected Flow
- **Bot responds immediately:** Typing indicator
- **Bot processes:** Parses intent, checks governance, executes agent
- **Bot responds with result:**
🤖 Executing Finance agent...
✅ Task completed in 2.5s
Status: All systems operational
Budget: $45,000 / $50,000
Active alerts: 0Step 5: Test Rich Features
5.1. Test Rich Formatting
/run Finance generate report --format jsonExpected: Code blocks with syntax highlighting
5.2. Test Media Support
/run Finance export chart --type pngExpected: Image file sent back
5.3. Test Dangerous Commands (2FA)
/run Finance delete_all_dataExpected:
⚠️ Dangerous command detected!
2FA required. Check your email for confirmation token.
Reply with: /confirm <token>Step 6: Test Rate Limiting
Send multiple commands rapidly:
/run Finance status
/run Finance status
/run Finance status
...After hitting limit (Free: 10/minute):
⚠️ Rate limit exceeded!
You've exceeded your plan's rate limit.
Free plan: 50 commands/day, 10/minute
Upgrade: https://atom-saas.com/upgradeStep 7: Test Account Linking UI (Frontend)
7.1. Access Dashboard
- Open Atom dashboard:
http://localhost:3000 - Navigate to Settings → Integrations → Telegram
- Click "Link Telegram Account"
7.2. Scan QR Code
- Dashboard shows QR code
- Send
/linkcommand to bot - Bot responds with QR code scan option
- Scan with Telegram app
7.3. Verify Linked Account
Dashboard shows:
Linked Accounts:
✅ Telegram (@your_username)
Linked: Feb 16, 2026
Chat ID: 123456789Troubleshooting
Issue: Webhook Not Receiving Updates
**Symptoms:** Bot doesn't respond to messages
**Solutions:**
- Verify webhook URL:
curl https://api.telegram.org/bot<token>/getWebhookInfo - Check backend logs:
tail -f backend-saas/logs/app.log - Ensure backend is running:
curl http://localhost:8000/api/gateway/health - Check firewall/ngrok is running
Issue: Account Linking Fails
**Symptoms:** /link command returns "Invalid token"
**Solutions:**
- Check token hasn't expired (1-hour expiry)
- Verify Redis is running:
redis-cli ping - Check backend logs for specific error
- Regenerate token via API
Issue: Command Execution Fails
**Symptoms:** Bot returns error instead of result
**Solutions:**
- Check agent exists and is active
- Verify tenant_id matches
- Check governance logs: Agent maturity too low?
- Review shell command approval (if applicable)
Issue: Rate Limiting Too Aggressive
**Symptoms:** Legitimate usage blocked
**Solutions:**
- Check Redis rate limit keys:
redis-cli keys "rate:*" - Verify plan tier in database
- Clear stale keys:
redis-cli DEL rate:tenant:<tenant_id> - Adjust limits in
abuse_protection_service.py
Debugging Commands
Check Bot Status
# Health check
curl http://localhost:8000/api/gateway/health
# Webhook info
curl "https://api.telegram.org/bot<token>/getWebhookInfo"
# Recent updates
curl "https://api.telegram.org/bot<token>/getUpdates?offset=-1"View Redis State
# Link tokens
redis-cli keys "link:*"
# Rate limit counters
redis-cli keys "rate:*"
# View specific token
redis-cli GET "link:abc123def456"Database Queries
-- Check linked accounts
SELECT * FROM user_accounts WHERE platform = 'telegram';
-- Check audit log
SELECT * FROM im_audit_log ORDER BY created_at DESC LIMIT 10;
-- Check link tokens
SELECT * FROM link_tokens WHERE used_at IS NULL;Performance Testing
Load Test Command Execution
# Install hey (HTTP load generator)
go install github.com/rakyll/hey@latest
# Test webhook endpoint (100 requests, 10 concurrent)
hey -n 100 -c 10 -H "Content-Type: application/json" \
-d '{"update_id":1,"message":{"chat":{"id":123456789},"text":"test"}}' \
http://localhost:8000/api/gateway/webhook/telegramMonitor Response Times
# Check backend logs for timing
tail -f backend-saas/logs/app.log | grep "duration_ms"Next Steps
After successful testing:
- **Deploy to Production:** Update webhook URL to production domain
- **Monitor Logs:** Set up log aggregation (Sentry, LogRocket)
- **Configure Alerts:** Rate limit alerts, error rate alerts
- **Scale Up:** Add Redis replica for token storage
- **Add More Platforms:** WhatsApp (Twilio), Signal (signal-cli)
Additional Resources
- **Telegram Bot API Docs:** https://core.telegram.org/bots/api
- **python-telegram-bot Docs:** https://python-telegram-bot.readthedocs.io/
- **Phase 37 Plans:**
.planning/phases/37-openclaw-integration/ - **Message Gateway Code:**
backend-saas/core/message_gateway.py
Checklist
- [ ] Telegram bot created via @BotFather
- [ ] Bot token added to environment variables
- [ ] Webhook URL configured
- [ ] Backend server running with migrations applied
- [ ] Redis instance running
- [ ] Account linking flow tested (token generation → linking)
- [ ] Command execution tested (simple command)
- [ ] Rich formatting tested (markdown, code blocks)
- [ ] Rate limiting tested (multiple rapid commands)
- [ ] 2FA flow tested (dangerous command)
- [ ] Dashboard UI tested (QR code scanning)
- [ ] Logs reviewed for errors
- [ ] Production webhook URL set (if deploying)
---
**Questions?** Check the Phase 37 summary documents or review the implementation code.